package com.rytx.common.core.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class ArtRedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 尝试获取分布式锁
     *
     * @param lockKey 锁的唯一键
     * @param requestId 请求的唯一ID（可以是UUID或其他唯一标识），用于释放锁时检查
     * @param expireTime 锁的过期时间（秒）
     * @return 如果获取到锁，返回true；否则返回false
     */
    public Boolean tryLock(String lockKey, String requestId, long expireTime) {
        return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
    }
    /**
     * 释放分布式锁
     *
     * @param lockKey 锁的唯一键
     * @param requestId 请求的唯一ID（用于验证锁是否由当前客户端持有）
     * @return 如果释放成功，返回true；否则返回false
     */
    public boolean unlock(String lockKey, String requestId) {
        if (lockKey == null || requestId == null) {
            return false;
        }

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                "    return redis.call('del', KEYS[1]) " +
                "else " +
                "    return 0 " +
                "end";

        try {
            Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList(lockKey), requestId);
            return result != null && result > 0;
        } catch (Exception e) {
            return false;
        }
    }

}
